package org.example.controller;


import lombok.extern.slf4j.Slf4j;
import org.example.mapper.SleepMapper;
import org.example.properties.ToolProperties;
import org.example.utils.AudioVolumeAnalyzer;
import org.example.utils.voice;
import org.example.utils.M4aToWav;
import org.example.pojo.Respw;
import org.example.pojo.SleepInfo;
import org.example.pojo.UserRequest;
import org.example.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/upload")
@CrossOrigin  // 添加跨域支持
public class UploadController {

    @Autowired
    private UploadALOSSController uploadALOSSController;

//    @Autowired
//    private ChatController chatController;

    @Autowired
    private SleepMapper sleepMapper;

    @Value("${file.upload-path}")
    private String uploadPath;

    @Value("${file.qiege-path}")
    private String qiegePath;

    //不靠谱
//    @Autowired
//    private ToolProperties toolProperties;
//    private String ffmpegPath;
//    @PostConstruct
//    public void init() {
//        this.ffmpegPath = toolProperties.getFfmpegPath();
//    }

    @Value("${tool.ffmpeg}")
    private String ffmpegPath;

    /**
     * 小程序录音文件上传
     */
    @PostMapping("/applet/voice")  // 明确指定POST方法
    @ResponseBody
    public Respw uploadVoice(@RequestParam("file") MultipartFile file, @RequestParam("username") String username) {
//        String ffmpegPath=toolProperties.getFfmpegPath();
        log.info("接收用户{}的文件",username);
        log.info("{}",file);

        try {
            //一、
            // 1.检查文件
            if (file.isEmpty()) {
//                return new Response(false, "获取录音失败", (List<String>) file);
                return new Respw(0, 0, new String[0]);
            }
            // 2.生成新文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString() + suffix;
            // 3.创建保存目录
            String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());        //当前日期 加上2024/12/7
            log.info("datePath="+datePath);
            //    url组成     E盘前缀  +username   + 创建时间   +文件名
            File uploadDir = new File(uploadPath + "/voice/" + username + "/" + datePath);       //完整文件夹路径 绝对路径
            File qiegeUrl = new File(qiegePath + "/voice/" + username + "/" + datePath);         //切割后的文件夹路径
            log.info("uploadDir=" + uploadDir);
            log.info("qiegeUrl=" + qiegeUrl);

            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            if (!qiegeUrl.exists()) {
                qiegeUrl.mkdirs();      //要创建下面才能正常执行
            }
            // 4.保存文件
            File destFile = new File(uploadDir, newFileName);
            file.transferTo(destFile);
            // 5.返回文件访问路径
            String fileUrl = "/voice/" + datePath + "/" + newFileName;


            //二、
            //1.整理M4A绝对路径
            String juedui = uploadDir + "/" + newFileName;            //绝对路径
            log.info(juedui + "             ....");
            //2. 把M4A转换成WAV
            //    outputFilePath为WAV路径
            // 输入 M4A 文件路径
            String inputFilePath = juedui;
            // 输出 WAV 文件路径
            UUID uuid = UUID.randomUUID(); // 生成一个随机UUID
            String uuidString = uuid.toString();
            String outputFilePath = qiegeUrl + "/" + uuidString + ".wav";  // 请替换为实际路径

            // 调用 FFmpeg 转换 M4A 为 WAV
            try {
                M4aToWav zhuanhuan = new M4aToWav();
                zhuanhuan.convertM4AToWav(ffmpegPath,inputFilePath, outputFilePath);
                log.info("转换成功！输出文件: " + outputFilePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("第二点完成");
            //分析WAV分贝最大值
            float max = 0;
            // 调用ffmpeg命令分析音频的最大分贝
            String command = ffmpegPath + " -i " + outputFilePath + " -filter:a volumedetect -f null /dev/null";
            try {
                // 执行命令并获取输出
                Process process = Runtime.getRuntime().exec(command);

                // 读取命令行输出
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream())); // 使用getErrorStream()来读取ffmpeg的输出
                String line;
                while ((line = reader.readLine()) != null) {
                    // 检查输出是否包含分贝信息
                    if (line.contains("max_volume")) {
                        // 提取最大分贝值
                        String maxVolume = line.split(":")[1].trim().split(" ")[0];
                        log.info("Max Volume (dB): " + maxVolume);
                        max = Float.parseFloat(maxVolume);

                    }
                }

                int exitCode = process.waitFor(); // 等待进程完成
                if (exitCode != 0) {
                    log.info("ffmpeg命令执行失败");
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }


            //3.把wav文件进行切割（按声音最高点进行切割成4段）
            //一切二
            long number = 1;
//            AudioVolumeAnalyzer ava=new AudioVolumeAnalyzer();
//            List all=ava.qiege(ffmpegPath,qiegeUrl,uuidString,number,outputFilePath);
//            String outputFile1 =all.get(0).toString();
//            String outputFile2 =all.get(1).toString();
//            number= (long) all.get(2);
//            log.info("第三点第一个切割完成" + outputFile1 + "     " + outputFile2);

            String outputFile1 = qiegeUrl + "/" + uuidString + number + ".wav";
            number++;
            String outputFile2 = qiegeUrl + "/" + uuidString + number + ".wav";
            number++;
            try {
                AudioVolumeAnalyzer audioVolumeAnalyzer2 = new AudioVolumeAnalyzer();
                float maxVolumeTimestamp = audioVolumeAnalyzer2.analyzeAudioVolume(outputFilePath);      //传入的参数outputFilePath为实际的完整的原wav路径
                // 根据最大音量时间切割音频
                audioVolumeAnalyzer2.splitAudioFile(outputFilePath, ffmpegPath, maxVolumeTimestamp, outputFile1, outputFile2);
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("第三点第一个切割完成" + outputFile1 + "     " + outputFile2);

            //上半切开
            String outputFile3 = qiegeUrl + "/" + uuidString + number + ".wav";
            number++;
            String outputFile4 = qiegeUrl + "/" + uuidString + number + ".wav";
            number++;
            try {
                AudioVolumeAnalyzer audioVolumeAnalyzer2 = new AudioVolumeAnalyzer();
                float maxVolumeTimestamp = audioVolumeAnalyzer2.analyzeAudioVolume(outputFile1);
                // 根据最大音量时间切割音频
                audioVolumeAnalyzer2.splitAudioFile(outputFile1, ffmpegPath, maxVolumeTimestamp, outputFile3, outputFile4);
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("第三点第二个切割完成" + outputFile3 + "     " + outputFile4);

            //下半切开
            String outputFile5 = qiegeUrl + "/" + uuidString + number + ".wav";
            number++;
            String outputFile6 = qiegeUrl + "/" + uuidString + number + ".wav";
            number++;
            try {
                AudioVolumeAnalyzer audioVolumeAnalyzer2 = new AudioVolumeAnalyzer();
                float maxVolumeTimestamp = audioVolumeAnalyzer2.analyzeAudioVolume(outputFile2);
                // 根据最大音量时间切割音频
                audioVolumeAnalyzer2.splitAudioFile(outputFile2, ffmpegPath, maxVolumeTimestamp, outputFile5, outputFile6);
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("第三点第三个切割完成" + outputFile5 + "     " + outputFile6);
            log.info("第三点全部完成");

            //4.将四个wav存储到阿里云中，并且要求将阿里云路径存储到mysql中
            //  将磁盘路径 转换成    MultipartFile
            MultipartFile multipartFile3 = FileUtils.convertToMultipartFile(outputFile3);
            MultipartFile multipartFile4 = FileUtils.convertToMultipartFile(outputFile4);
            MultipartFile multipartFile5 = FileUtils.convertToMultipartFile(outputFile5);
            MultipartFile multipartFile6 = FileUtils.convertToMultipartFile(outputFile6);
            //上传到阿里云
            String upload3 = uploadALOSSController.upload(multipartFile3);
            log.info("      3    " + multipartFile3);
            String upload4 = uploadALOSSController.upload(multipartFile4);
            log.info("     4     " + multipartFile4);
            String upload5 = uploadALOSSController.upload(multipartFile5);
            log.info("     5   " + multipartFile5);
            String upload6 = uploadALOSSController.upload(multipartFile6);
            log.info("     6    " + multipartFile6);
            log.info("上传阿里云");
            //存储到mysql
            String voices = "";
            try {
                voices = new voice().analyzeAudioVolumeVoice(outputFilePath); //记录每秒分贝大小
            } catch (Exception e) {
                e.printStackTrace();
            }
            long timestamp = System.currentTimeMillis(); //获取当前时间戳（毫秒级）
            sleepMapper.insertSleepRecord(timestamp, username, juedui, upload3, upload4, upload5, upload6, voices);//往数据库中插入数据
            log.info("第四点完成");

//            List<String> audioList = new ArrayList<>();
//            audioList.add(outputFile3);
//            audioList.add(outputFile4);
//            audioList.add(outputFile5);
//            audioList.add(outputFile6);
//            log.info(outputFile1+"    "+outputFile2+"                   897979");
//            log.info("分贝最大值 "+max);

            voices = voices.trim(); //第一个字符不是空格，这里为了保险，删除了两端的空格
            String[] voiceSpilt = voices.split(" ");     //把分贝数据切割
//            String[] voiceSpilt = new String[split.length];
//            for (int i = 1; i < split.length; i++) {
//                voiceSpilt[i - 1] = split[i];
//            }

            log.info("返回的值：{}；{}；{}",timestamp, max, voiceSpilt);
            return new Respw(timestamp, max, voiceSpilt);
        } catch (Exception e) {
            e.printStackTrace();
//            return "文件上传失败：" + e.getMessage();
//            return new Response(false, "文件上传失败", (List<String>) file);
            return new Respw(0, 0, new String[0]);
        }
    }


    /*
    * 获取4个音频文件路径
    * */
    @PostMapping("/voice")
    public List<String> getAudioFile(@RequestBody UserRequest userRequest) throws IOException {
        // 定义4个音频文件路径
//        String[] fileNames = {"E:\\project\\weixin\\切割\\voice\\zhangsan\\2024\\12\\07/fbdec0ea-e7b1-42f4-8e5e-5f5cbe5f207f3.wav", "E:\\project\\weixin\\切割\\voice\\zhangsan\\2024\\12\\07/fbdec0ea-e7b1-42f4-8e5e-5f5cbe5f207f4.wav", "audio3.wav", "audio4.wav"};
//        Map<String, String> audioFiles = new HashMap<>();
//
//        // 循环读取每个音频文件的字节流
//        for (String fileName : fileNames) {
//            String audioFilePath = "server/audio/" + fileName;
//            File audioFile = new File(audioFilePath);
//
//            if (!audioFile.exists()) {
//                return ResponseEntity.notFound().build();
//            }
//
//            // 将音频文件内容转为Base64编码的字符串
//            try (InputStream inputStream = new FileInputStream(audioFile)) {
//                byte[] audioBytes = inputStream.readAllBytes();
//                String encodedAudio = Base64.getEncoder().encodeToString(audioBytes);
//                audioFiles.put(fileName, encodedAudio);
//            }
//        }
        List<String> list = new ArrayList<>();
        log.info(userRequest.getUserId() + " " + userRequest.getUsername() + "      69966");

//        根据音频ID和username从数据库中获取对应切割的音频
        SleepInfo yinByusernamesAndId = sleepMapper.getYinByusernamesAndId(userRequest.getUserId(), userRequest.getUsername());

        list.add(yinByusernamesAndId.getSleep1());
        list.add(yinByusernamesAndId.getSleep2());
        list.add(yinByusernamesAndId.getSleep3());
        list.add(yinByusernamesAndId.getSleep4());
        log.info("yinpin1   " + yinByusernamesAndId.getSleep1());
        log.info("yinpin2   " + yinByusernamesAndId.getSleep2());
        log.info("yinpin3   " + yinByusernamesAndId.getSleep3());
        log.info("yinpin4   " + yinByusernamesAndId.getSleep4());
//        list.add( "https://web-canqiong.oss-cn-beijing.aliyuncs.com/b0b89b65-b2d2-4639-8469-d5e8a3ef136c.wav");
//        list.add("https://web-canqiong.oss-cn-beijing.aliyuncs.com/af3933eb-8c81-40a6-8996-d093fd24dbc26.wav");
//        list.add( "https://web-canqiong.oss-cn-beijing.aliyuncs.com/af3933eb-8c81-40a6-8996-d093fd24dbc25.wav");

        // 返回包含所有音频字节流的响应
        return list;
    }


    // 添加一个测试接口
    @GetMapping("/test")
    @ResponseBody
    public String test(String username) {
        log.info("接收成功");
        log.info(username);

        return "接口正常";
    }
}
